package com.maybach.core.ao.impl;

import com.maybach.common.model.OperateLogDO;
import com.maybach.common.query.OperateLogQuery;
import com.maybach.core.ao.OperateLogAO;
import com.maybach.core.manager.OperateLogManager;
import com.maybach.dubbo.api.model.OperateLogModel;
import com.maybach.util.AssertUtil;
import com.maybach.util.query.support.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 操作日志AO实现 Created by chris on 16/3/29. e-mail baijun@maihaoche.com
 */
@Component
public class OperateLogAOImpl implements OperateLogAO {

	@Autowired
	OperateLogManager operateLogManager;

	@Override
	public Long addOperateLog(OperateLogModel model) {
		OperateLogDO operateLogDO = this.assemblyOperateLogDO(model);
		operateLogManager.insertSelective(operateLogDO);
		return operateLogDO.getId();
	}

	/**
	 * 对象转换
	 *
	 * @param model
	 * @return
	 */
	private OperateLogDO assemblyOperateLogDO(OperateLogModel model) {
		AssertUtil.notNull(model, "model");
		OperateLogDO operateLogDO = new OperateLogDO();
		operateLogDO.setActorResult(model.getActorResult());
		operateLogDO.setActType(model.getActType());
		operateLogDO.setMemo(model.getMemo());
		operateLogDO.setReportUrl(model.getReportUrl());
		operateLogDO.setUserId(model.getUserId());
		operateLogDO.setId(model.getId());
		return operateLogDO;
	}

	@Override
	public boolean updateOperateLog(OperateLogModel model) {
		OperateLogDO operateLogDO = this.assemblyOperateLogDO(model);

		return operateLogManager.updateByPrimaryKeySelective(operateLogDO) > 0;
	}

	@Override
	public PageResult<OperateLogDO> queryOperateLog(OperateLogModel model) {
		OperateLogQuery operateLogQuery = this.assemblyQuery(model);
		return operateLogManager.selectByQueryWithPage(operateLogQuery);
	}

	/**
	 * 对象转换
	 *
	 * @param model
	 * @return
	 */
	private OperateLogQuery assemblyQuery(OperateLogModel model) {
		AssertUtil.notNull(model, "model");
		OperateLogQuery query = new OperateLogQuery();
		OperateLogQuery.Criteria criteria = query.or();
		query.setPageNo(model.getPageNo());
		query.setPageSize(model.getPageSize());

		if (StringUtils.isNotBlank(model.getActType())) {
			criteria.andActTypeEqualTo("%" + model.getActType() + "%");
		}
		if (StringUtils.isNotBlank(model.getActorResult())) {
			criteria.andActTypeEqualTo("%" + model.getActorResult() + "%");
		}
		if (null != model.getId()) {
			criteria.andIdEqualTo(model.getId());
		}
		if (null != model.getStartDate() && null != model.getEndDate()
				&& model.getStartDate().before(model.getEndDate())) {
			criteria.andGmtCreateBetween(model.getStartDate(), model.getEndDate());
		}
		query.setOrderByClause("id desc");
		return query;
	}

}
